#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Author:    御风
# @Mail:      zhong.yufeng@foxmail.com
# @Time:      2022/4/12 3:46


import time
from flask import current_app as app
from modules.admin import AdminDataBase
from utils.result import ApiResult
from utils.session.session import Session


def checkLogin():
    try:
        msg = None
        isLogin = False
        session = Session.get()
        adminLoginTime = session.get("adminLoginTime", 0)
        adminId = session.get("adminId", None)
        adminAccount = session.get("adminAccount", None)
        adminPassword = session.get("adminPassword", None)
        if isinstance(adminLoginTime, int) and (int(time.time()) - adminLoginTime) < Session.timeMaxLogin:
            if adminId is not None and adminAccount is not None and adminPassword is not None:
                db = AdminDataBase()
                info = db.query(adminAccount, adminPassword)
                if not info:
                    msg = "登录信息已失效"
                else:
                    if not info.get("valid"):
                        msg = "帐号禁止登录"
                    else:
                        isLogin = True
        if not isLogin:
            if not msg:
                msg = "未登录"
            session.pop("adminId", None)
            session.pop("adminAccount", None)
            session.pop("adminPassword", None)
            session.pop("adminCaptchaCode", None)
            session.pop("adminCaptchaTime", None)
            Session.set(session)
            return ApiResult.error(100001, msg=msg)
    except Exception as e:
        app.logger.exception(e)
        return ApiResult.error(-1, msg="失败")
